<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-13 16:22:13
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-09
-->
<template>
  <RjModal
    width="600px"
    drag
    :title="$t('userManage.batchModalTitle')"
    :visible="isVisible"
    :footer="null"
    @cancel="onCancel"
  >
    <a-form-model
      :labelCol="{ span: 6 }"
      :wrapperCol="{ span: 18 }"
      labelAlign="left"
      :model="form"
      ref="form"
      :colon="false"
    >
      <div>
        {{ $t('common.importTip') }}
      </div>
    </a-form-model>
    <ExcelImport
      :showUploadList="false"
      :filterVal="filterVal"
      :tHeader="tHeader"
      @importCallBack="importCallBack"
      templateName="authAccountTemplate"
    />
  </RjModal>
</template>

<script>
import { mapState } from 'vuex';
import ExcelImport from '@/components/excel/excelImport';
import { requestHttp, maccApi } from '@utils/index';
import { ValiDateTools } from '@/utils';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
export default {
  mixins: [authSysMixin],
  components: {
    ExcelImport,
  },
  data() {
    const tHeader = [
      this.$t('localAccount.name'),
      this.$t('userManage.password'),
      this.$t('localAccount.authPolicy'),
      this.$t('userManage.firstName'),
      this.$t('userManage.lastName'),
      this.$t('userManage.email'),
      this.$t('userManage.alias'),
      this.$t('userManage.phone'),
    ];
    const filterVal = [
      'Account',
      'Password',
      'User group',
      'First name',
      'Last name',
      'Email',
      'Alias',
      'phone',
    ];
    return {
      isVisible: false,
      form: {},
      confirmLoading: false,
      file: {},
      fileList: [],
      actionUrl: `/webproxy/common/excel/parse`,
      tHeader,
      filterVal,
    };
  },
  computed: {
    ...mapState('AuthCommon', ['authPolicys']),

    authPolicyMap() {
      const tempMap = {};
      this.authPolicys.forEach((item) => {
        tempMap[item.name] = item.uuid;
      });
      return tempMap;
    },
  },
  methods: {
    onCancel() {
      this.isVisible = false;
    },
    openModal() {
      this.isVisible = true;
    },
    getFailIcon() {
      return <a-icon style={{ color: 'red' }} type="info-circle" />;
    },
    getToImportFailReason(unvalidRows) {
      return unvalidRows.length < 10 ? (
        <div>
          {this.$t('userManage.reenter', {
            rows: unvalidRows.join('、'),
          })}
        </div>
      ) : (
        <div>
          {this.$t('userManage.reenter', {
            rows: `${unvalidRows[0]}、${unvalidRows[1]}、${unvalidRows[2]}、${unvalidRows[3]}、${unvalidRows[4]}…`,
          })}
        </div>
      );
    },
    getImportedFailReason(res) {
      res.failedList.map((item) => {
        return (
          (item.failedLineNumList.length >= 10 && (
            <div>
              {this.$t('userManage.batchUploadFailed', {
                rows: `${item.failedLineNumList[0]}、${item.failedLineNumList[1]}、${item.failedLineNumList[2]}、${item.failedLineNumList[3]}、${item.failedLineNumList[4]}...`,
                reason: item.failedDesc,
              })}
              <br />
            </div>
          )) || (
            <div>
              {this.$t('userManage.batchUploadFailed', {
                rows: item.failedLineNumList.join('、'),
                reason: item.failedDesc,
              })}
              <br />
            </div>
          )
        );
      });
    },
    async importCallBack(list) {
      let params = [];
      let {
        alphaNumericUnderscoreRegex,
        alphaNumericUnderscoreBlankRegex,
        emailRegex,
      } = ValiDateTools;
      let flag = false;
      let unvalidRows = [];
      list.forEach((item, index) => {
        const firstName = 'First name';
        const lastName = 'Last name';
        const userGroup = 'User group';
        const accountFlag = alphaNumericUnderscoreRegex.test(item.Account);
        const passwordFlag = /^[a-zA-Z0-9<=>\\[\]!@#$*().\x22]{2,32}$/.test(
          item.Password
        );
        // const firstNameFlag = alphaNumericUnderscoreRegex.test(item[firstName]);
        // const lastNameFlag = alphaNumericUnderscoreRegex.test(item[lastName]);
        // const aliasFlag = alphaNumericUnderscoreBlankRegex.test(item.Alias);
        const firstNameFlag = item[firstName] && item[firstName].length <= 60;
        const lastNameFlag = item[lastName] && item[lastName].length <= 60;
        const aliasFlag = item.Alias && item.Alias.length <= 60;
        if (
          !/^[\u4E00-\u9FA5A-Za-z0-9_@\\<\\=\\>\\[\]\\!\\#\\$\\*\\(\\)\\.]+$/.test(
            item[userGroup]
          ) ||
          !accountFlag ||
          !passwordFlag ||
          (item.Account &&
            (item.Account.length < 1 || item.Account.length > 32)) ||
          (item.Password &&
            (item.Password.length < 2 || item.Password.length > 32)) ||
          (item.Email && !emailRegex.test(item.Email)) ||
          (item[firstName] && !firstNameFlag) ||
          (item[lastName] && !lastNameFlag) ||
          (item.Alias && !aliasFlag)
        ) {
          flag = true;
          unvalidRows.push(index + 2);
        } else {
          params.push({
            profileId: this.authPolicyMap[item[userGroup]] || '',
            username: item.Account || '',
            password: item.Password || '',
            firstName: item[firstName] || '',
            lastName: item[lastName] || '',
            comment: item.Alias || '',
            refName: '',
            email: item.Email || '',
            lineNum: index + 2,
          });
        }
      });

      if (flag) {
        this.$confirm({
          title: this.$t('userManage.batchUploadFailedTitle'),
          cancelButtonProps: {
            style: {
              display: 'none',
            },
          },
          content: () => this.getToImportFailReason(unvalidRows),
        });
        return;
      }
      let querys = {
        tenantId: this.tenantInfo.tenantId,
        group_id: this.groupId,
      };
      let replaces = {
        tenantName: this.tenantInfo.tenantName,
        userName: encodeURI(this.userInfo.account),
        groupId: this.groupId,
      };
      this.loading = true;
      let res = await this.requestHttpAuth({
        api: maccApi.MACC_ACCOUNT_BATCH_ADD_POST_API,
        method: 'POST',
        querys,
        params,
        replaces,
      });
      res = res.data; // 接口透传多了一层
      if (!res.code) {
        if (!res?.voucherData?.code) {
          if (!res.failedList) {
            this.isVisible = false;
            this.$emit('refreshList');
            this.$message.success(this.$t('userManage.success'));
          } else {
            this.$confirm({
              title: this.$t('userManage.batchUploadFailedTitle'),
              icon: () => this.getFailIcon(),
              cancelButtonProps: {
                style: {
                  display: 'none',
                },
              },
              content: () => this.getImportedFailReason(res),
            });
          }
        } else {
          this.$message.warning(res.voucherData.msg);
        }
      } else {
        if (!res.failedList) {
          this.$message.warning(res.msg);
        } else {
          this.$confirm({
            title: this.$t('userManage.batchUploadFailedTitle'),
            icon: () => this.getFailIcon(),
            cancelButtonProps: {
              style: {
                display: 'none',
              },
            },
            content: () => this.getImportedFailReason(res),
          });
        }
      }
      this.$emit('ok');
    },
  },
};
</script>

<style lang="less" scoped></style>
